﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AngleSharp;
using AngleSharp.Dom;
using System.Threading.Tasks;
using AngleSharp.Parser.Html;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.Win32;
using System.Diagnostics;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
using BaseEpub;

namespace AngleSharpDemo
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {

            //Create a (re-usable) parser front-end
            var parser = new HtmlParser();
            //Source to be pared
            var source = "<h1>Some example source</h1><p>This is a paragraph element";
            //Parse source to document
            var document = parser.Parse(source);

            //Do something with document like the following

            Console.WriteLine("Serializing the (original) document:");
            Console.WriteLine(document.DocumentElement.OuterHtml);

            var p = document.CreateElement("p");
            p.TextContent = "This is another paragraph.";

            Console.WriteLine("Inserting another element in the body ...");
            document.Body.AppendChild(p);

            Console.WriteLine("Serializing the document again:");
            Console.WriteLine(document.DocumentElement.OuterHtml);
        }

        [TestMethod]
        public void ZipTest()
        {
            try
            {
                UnZip(@"E:\MyCode\NetCode\AngleSharpDemo\有机化学样本3\有机化学样本3.epub", @"E:\MyCode\NetCode\AngleSharpDemo\有机化学样本3\有机化学样本3", "123", true);
                //uncompress(@"E:\MyCode\NetCode\AngleSharpDemo\有机化学样本3.rar", @"E:\MyCode\NetCode\AngleSharpDemo\有机化学样本3\");  //已经存在的文件会发生异常
                /* 注册表异常解决：
                 * 此时会提示：未将对象引用设置为对象的实例

解决办法：修改注册表，添加如下项：
HKEY_CLASSES_ROOT\Applications\WinRAR.exe\Shell\Open\Command 
值为："C:\Program Files (x86)\WinRAR\WinRAR.exe" "%1"
                 
                 */
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        /// <summary>
        /// 读取目录ncx文件
        /// </summary>
        [TestMethod]
        public void ReadNcx()
        {
            try
            {
                string ncxPath = @"E:\MyCode\NetCode\AngleSharpDemo\有机化学样本3\有机化学样本3\OEBPS\toc.ncx";
                //string ss = System.IO.File.ReadAllText(ncxPath);
                //XmlDocument doc = new XmlDocument();
                //string guid = Guid.NewGuid().ToString("N");
                new NdsNcx().GetContent(ncxPath);

                ////XDocument xd = XDocument.Load(ncxPath);
                ////XElement root = xd.Root;
                ////IEnumerable<XElement> ncx = root.Elements();
                ////IList<string> ll = new List<string>();


                //XElement xe = XElement.Load(ncxPath);

                //eles.Elements();
                //IEnumerable<XNode> xns = xe.Nodes();
                //foreach (XNode item in xns)
                //{
                //    XNode xN = item.NextNode;
                //}






                //doc.Load(ncxPath);
                ////目录的根节点
                //XmlNodeList node = doc.GetElementsByTagName("navMap"); //navMap
                ////读取章
                //XmlNodeList chapterNodes = node[0].ChildNodes;  //navPoint
                //foreach (XmlNode chapter in chapterNodes)
                //{
                //    XmlNodeList secFirNodes = chapter.SelectNodes("navPoint");
                //    //节
                //    //XmlNodeList secFirNodes = chapter.ChildNodes;
                //    if (secFirNodes != null && secFirNodes.Count > 0)
                //    {
                //        //小节
                //        foreach (XmlNode secSec in secFirNodes)
                //        {

                //        }
                //    }
                //}
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        [TestMethod]
        public void NdPressOpf()
        {
            IOpfBase opf = new NdPressOpf();
            string opfPath = @"E:\MyCode\NetCode\AngleSharpDemo\有机化学样本3\有机化学样本3\OEBPS\content.opf";
            opf.GetEbookInfo(opfPath);
        }

        [TestMethod]
        public void NdPressNcx()
        {
            try
            {
                INcxBase ncx = new NdPressNcx();
                string ncxPath = @"E:\MyCode\NetCode\AngleSharpDemo\有机化学样本3\有机化学样本3\OEBPS\toc.ncx";
                IList<SectionBaseInfo> secList = ncx.GetSecList(ncxPath);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            
        }

        /// <summary>
        /// 解压缩一个 zip 文件。
        /// </summary>
        /// <param name="zipedFile">The ziped file.</param>
        /// <param name="strDirectory">The STR directory.</param>
        /// <param name="password">zip 文件的密码。</param>
        /// <param name="overWrite">是否覆盖已存在的文件。</param>
        public void UnZip(string zipedFile, string strDirectory, string password, bool overWrite)
        {

            if (strDirectory == "")
                strDirectory = Directory.GetCurrentDirectory();
            if (!strDirectory.EndsWith("\\"))
                strDirectory = strDirectory + "\\";

            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipedFile)))
            {
                s.Password = password;
                ZipEntry theEntry;

                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directoryName = "";
                    string pathToZip = "";
                    pathToZip = theEntry.Name;

                    if (pathToZip != "")
                        directoryName = Path.GetDirectoryName(pathToZip) + "\\";

                    string fileName = Path.GetFileName(pathToZip);

                    Directory.CreateDirectory(strDirectory + directoryName);

                    if (fileName != "")
                    {
                        if ((File.Exists(strDirectory + directoryName + fileName) && overWrite) || (!File.Exists(strDirectory + directoryName + fileName)))
                        {
                            using (FileStream streamWriter = File.Create(strDirectory + directoryName + fileName))
                            {
                                int size = 2048;
                                byte[] data = new byte[2048];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);

                                    if (size > 0)
                                        streamWriter.Write(data, 0, size);
                                    else
                                        break;
                                }
                                streamWriter.Close();
                            }
                        }
                    }
                }

                s.Close();
            }
        }

        /// <summary>
        /// //解压  必须装有WinRar
        /// </summary>
        /// <param name="rarfilepath"></param> //压缩文件路劲
        /// <param name="filepath"></param>   //解压保存路径
        protected string uncompress(string rarfilepath, string filepath)
        {
            //"D:\Program Files (x86)\WinRAR\WinRAR.exe" x -t -o-p E:\MyCode\NetCode\AngleSharpDemo\有机化学样本3.rar E:\MyCode\NetCode\AngleSharpDemo\有机化学样本3\      //在doc的解压命令
            try
            {
                string rar;
                RegistryKey reg;
                string args;
                ProcessStartInfo startInfo;
                Process process;
                reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command");//WinRar位置
                rar = reg.GetValue("").ToString();
                reg.Close();
                rar = rar.Substring(1, rar.Length - 7);
                args = " x -t -o-p " + rarfilepath + " " + filepath;
                startInfo = new ProcessStartInfo();
                startInfo.FileName = rar;
                startInfo.Arguments = args;
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                process = new Process();
                process.StartInfo = startInfo;
                process.Start();
                return "success";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

    }
}
